package com.tanhua.admin.service;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.domain.Analysis;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2021/12/10 10:47
 */
@Service
public class AnalysisService {

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private AnalysisMapper analysisMapper;


    public Integer queryCumulativeUsers() {
        return analysisMapper.queryCumulativeUsers();
    }

    public Analysis querySummary(Date now) {
        //5、根据当前时间查询AnalysisByDay数据
        LambdaQueryWrapper<Analysis> qw = Wrappers.<Analysis>lambdaQuery();
        qw.eq(Analysis::getRecordDate, DateUtil.format(now, "yyyy-MM-dd"));
        return analysisMapper.selectOne(qw);
    }


    public void analysis() throws ParseException {

        // 1. 定期查询的日期
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String yesterday = DateUtil.yesterday().toString("yyyy-MM-dd");
        // 2. 统计数量--注册数量
        Integer registerCount = logMapper.qurryTypeAndLogTime("0102", today);
        // 3. 统计数量--登录数量
        Integer loginCount = logMapper.qurryTypeAndLogTime("0101", today);
        // 4. 统计数量--活跃数量
        Integer activeCount = logMapper.queryByLogTime(today);
        // 5. 统计数量--次日留存
        Integer numRetention1d = logMapper.queryNumRetention1d(today, yesterday);
        // 6. 根据日期查询数据
        QueryWrapper<Analysis> qw = new QueryWrapper<Analysis>();
        qw.eq("record_date",new SimpleDateFormat("yyyy-MM-dd").parse(today));
        //7. 构造analysis对象
        Analysis analysis = analysisMapper.selectOne(qw);
        //8. 如果存在更新，如果不存在保存
        if(analysis != null) {
            analysis.setNumRegistered(registerCount);
            analysis.setNumLogin(loginCount);
            analysis.setNumActive(activeCount);
            analysis.setNumRetention1d(numRetention1d);
            analysisMapper.updateById(analysis);
        }else {
            analysis = new Analysis();
            analysis.setNumRegistered(registerCount);
            analysis.setNumLogin(loginCount);
            analysis.setNumActive(activeCount);
            analysis.setNumRetention1d(numRetention1d);
            analysis.setRecordDate(new SimpleDateFormat("yyyy-MM-dd").parse(today));
            analysis.setCreated(new Date());
            analysis.setUpdated(new Date());
            analysisMapper.insert(analysis);
        }
    }
}
